package com.cares.core.mng.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cares.core.base.controller.BaseController;
import com.cares.core.mng.service.RoleService;
import com.cares.core.utils.oConvertUtils;
import com.cares.entity.base.DataGridModel;
import com.cares.entity.base.PageModel;
import com.cares.entity.mng.Role;

/**
 * 角色管理的Controller.
 * 
 * @author
 */
@SuppressWarnings("unchecked")
@Controller
@RequestMapping(value = "/Mng/role")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;

	/**
	 * GET方法，角色列表页面加载
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model) {
		List<Role> roles = roleService.getAllRole();
		model.addAttribute("roles", roles);
		return "frm/mng/role/roleList";
	}

	/**
	 * 查询角色列表信息
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public void getDateGrid(DataGridModel dgm, Role role,
			HttpServletResponse response) {

		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		PageModel<Role> pageModel = new PageModel<Role>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(role);
		String result = this.roleService.getRoles(pageModel);
		System.out.println(result);
		try {
			this.renderText(response, result);
		} catch (IOException e) {
		}
	}

	/**
	 * 查询所有角色信息
	 */
	@RequestMapping(value = "/alllist", method = RequestMethod.POST)
	public void alllist(DataGridModel dgm, Role role,
			HttpServletResponse response) {

		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		pageNo = 1;
		pageSize = 10000;
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		PageModel<Role> pageModel = new PageModel<Role>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(role);
		String result = this.roleService.getRoles(pageModel);
		System.out.println(result);
		try {
			this.renderText(response, result);
		} catch (IOException e) {
		}
	}

	/**
	 * 跳转至新增或修改页面
	 * @return
	 */
	@RequestMapping(value = "/addWin", method = RequestMethod.GET)
	public String addWin(HttpServletRequest request) {
		String opt = oConvertUtils.getString(request.getParameter("opt"));
		request.setAttribute("opt", opt);
		return "frm/mng/role/roleAdd";
	}

	/**
	 * 获取所有角色MAP
	 * @return
	 */
	@RequestMapping(value = "/allRoles")
	public @ResponseBody
	Map all() {
		Map map = new HashMap();
		List<Role> roles = null;
		try {
			roles = roleService.getAllRole();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put(AJAX_MESSAGE, "true");
		map.put("rolelist", roles);
		return map;
	}

	/**
	 * 新增或修改角色
	 * @param role
	 * @return
	 */
	@RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, String> add(@RequestBody Role role, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>(1);
		String opt = oConvertUtils.getString(request.getParameter("opt"));
		try {
			if ("E".equals(opt)) {
				//XXX 存在问题，可修改为存在的角色名称
				roleService.updateRole(role);
			} else if (roleService.findRoleByName(role.getRoleName()) != null) {
				map.put(AJAX_MESSAGE, "false");
				map.put("check_name", "false");
				return map;
			} else {
				roleService.saveRole(role);
			}
			map.put(AJAX_MESSAGE, "true");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "fasle");
		}
		return map;
	}

	/**
	 * 删除角色
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> delete(@PathVariable("id")
	Long id) {
		
		Map<String, String> map = new HashMap<String, String>(1);
		try {
			roleService.deleteRole(id);
			map.put(AJAX_MESSAGE, "true");
		} catch (Exception e) {
			map.put(ERR_MESSAGE, "操作失败！");
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}

	/**
	 * 新增或更新角色菜单关联信息
	 * @param funcIdString
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "/updateRoleAuthority/{id}/{ids}/{stmp}", method = RequestMethod.GET)
	public @ResponseBody Map addRoleMenu(@PathVariable("ids") List<String> funcIdString, @PathVariable("id")
	Long roleId) {
		Map map = new HashMap();
		try {
			
			roleService.updateRoleAuth(roleId, funcIdString);
			map.put(AJAX_MESSAGE, "true");
		} catch (Exception e) {
			e.printStackTrace();
			map.put(ERR_MESSAGE, "操作失败！");
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}
 

	/**
	 * 删除角色菜单关联信息
	 * @param id
	 * @param mid
	 * @return
	 */
	@RequestMapping(value = "/delRoleMenu/{id}/{mid}", method = RequestMethod.GET)
	public @ResponseBody
	Map delRoleMenus(@PathVariable("id")
	Long id, @PathVariable("mid")
	Long mid) {
		Map map = new HashMap();
		try {
			map.put("id", id);
			map.put("mid", mid);
			roleService.delRoleMenu(map);
			map.put(AJAX_MESSAGE, "true");
		} catch (Exception e) {
			map.put(ERR_MESSAGE, "操作失败！");
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}
 
	/**
	 * 获取角色菜单信息
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getRoleMenus/{id}/{stp}", method = RequestMethod.GET)
	public @ResponseBody
	Map getRoleMenus(@PathVariable("id") Long id) {
		Map map = new HashMap();
		try {
			List<Map> list = roleService.getRoleMenus(id);
			List<String> authList=new ArrayList<String>();
			for(Map auth:list){//ROLEID,MENUID,FUNC
				if(null==auth.get("func")){
					authList.add(String.valueOf(auth.get("menuId")));
				}else{
					String[] func = String.valueOf(auth.get("func")).split(";");
					if(func.length>0){
						for(int i=0;i<func.length;i++){
							if(func[i].length()>0){
								authList.add(auth.get("menuId")+"-"+func[i]);
							}
						}
					}
				}
			}
			map.put("rmenus", authList);
			map.put(AJAX_MESSAGE, "true");
		} catch (Exception e) {
			map.put(ERR_MESSAGE, "操作失败！");
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadRole")
	public Role getRole(@RequestParam(value = "id", required = false)
	Long id) {
		if (id != null) {
			return roleService.getRole(id);
		}
		return null;
	}
	
}
